//! # 系统信息收集模块
//!
//! 提供系统状态、性能指标和资源使用情况的收集功能

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::RwLock;
use std::sync::Arc;

use crate::{AdminResult, AdminError};

/// 系统信息收集器
pub struct SystemInfoCollector {
    cache: Arc<RwLock<SystemInfoCache>>,
    cache_ttl: Duration,
}

/// 系统信息缓存
#[derive(Debug, Clone)]
struct SystemInfoCache {
    info: SystemInformation,
    last_updated: SystemTime,
}

/// 完整的系统信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemInformation {
    /// 基本信息
    pub basic: BasicInfo,
    /// 硬件信息
    pub hardware: HardwareInfo,
    /// 性能指标
    pub performance: PerformanceMetrics,
    /// 网络信息
    pub network: NetworkInfo,
    /// 进程信息
    pub processes: Vec<ProcessInfo>,
    /// 环境变量（过滤敏感信息）
    pub environment: HashMap<String, String>,
}

/// 基本系统信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BasicInfo {
    /// 主机名
    pub hostname: String,
    /// 操作系统
    pub os_name: String,
    /// 操作系统版本
    pub os_version: String,
    /// 系统架构
    pub architecture: String,
    /// 内核版本
    pub kernel_version: String,
    /// 启动时间
    pub boot_time: u64,
    /// 运行时间（秒）
    pub uptime_secs: u64,
}

/// 硬件信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HardwareInfo {
    /// CPU 信息
    pub cpu: CpuInfo,
    /// 内存信息
    pub memory: MemoryInfo,
    /// 磁盘信息
    pub disks: Vec<DiskInfo>,
}

/// CPU 信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CpuInfo {
    /// CPU 核心数
    pub cores: usize,
    /// CPU 逻辑核心数
    pub logical_cores: usize,
    /// CPU 型号
    pub model: String,
    /// CPU 频率 (MHz)
    pub frequency_mhz: f64,
    /// CPU 使用率（百分比）
    pub usage_percent: f64,
    /// 负载平均值 [1分钟, 5分钟, 15分钟]
    pub load_average: [f64; 3],
}

/// 内存信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryInfo {
    /// 总内存 (MB)
    pub total_mb: u64,
    /// 可用内存 (MB)
    pub available_mb: u64,
    /// 已使用内存 (MB)
    pub used_mb: u64,
    /// 空闲内存 (MB)
    pub free_mb: u64,
    /// 缓存内存 (MB)
    pub cached_mb: u64,
    /// 缓冲区内存 (MB)
    pub buffers_mb: u64,
    /// 使用率（百分比）
    pub usage_percent: f64,
    /// 交换分区总大小 (MB)
    pub swap_total_mb: u64,
    /// 交换分区已使用 (MB)
    pub swap_used_mb: u64,
}

/// 磁盘信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiskInfo {
    /// 设备名称
    pub name: String,
    /// 挂载点
    pub mount_point: String,
    /// 文件系统类型
    pub filesystem: String,
    /// 总大小 (GB)
    pub total_gb: u64,
    /// 已使用 (GB)
    pub used_gb: u64,
    /// 可用空间 (GB)
    pub available_gb: u64,
    /// 使用率（百分比）
    pub usage_percent: f64,
    /// 是否为只读
    pub read_only: bool,
}

/// 性能指标
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceMetrics {
    /// CPU 温度（如果可用）
    pub cpu_temperature: Option<f64>,
    /// 系统负载
    pub system_load: f64,
    /// 网络 I/O
    pub network_io: NetworkIo,
    /// 磁盘 I/O
    pub disk_io: DiskIo,
    /// 进程统计
    pub process_stats: ProcessStats,
}

/// 网络 I/O 统计
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkIo {
    /// 接收字节数
    pub bytes_received: u64,
    /// 发送字节数
    pub bytes_sent: u64,
    /// 接收包数
    pub packets_received: u64,
    /// 发送包数
    pub packets_sent: u64,
    /// 错误数
    pub errors: u64,
}

/// 磁盘 I/O 统计
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiskIo {
    /// 读取字节数
    pub read_bytes: u64,
    /// 写入字节数
    pub write_bytes: u64,
    /// 读取次数
    pub read_count: u64,
    /// 写入次数
    pub write_count: u64,
    /// I/O 时间 (ms)
    pub io_time_ms: u64,
}

/// 进程统计
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessStats {
    /// 总进程数
    pub total_processes: u32,
    /// 运行中进程数
    pub running_processes: u32,
    /// 睡眠进程数
    pub sleeping_processes: u32,
    /// 僵尸进程数
    pub zombie_processes: u32,
}

/// 网络信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkInfo {
    /// 网络接口
    pub interfaces: Vec<NetworkInterface>,
    /// TCP 连接统计
    pub tcp_connections: TcpStats,
}

/// 网络接口
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkInterface {
    /// 接口名称
    pub name: String,
    /// IP 地址
    pub ip_addresses: Vec<String>,
    /// MAC 地址
    pub mac_address: Option<String>,
    /// 是否启用
    pub is_up: bool,
    /// 接收字节数
    pub bytes_received: u64,
    /// 发送字节数
    pub bytes_sent: u64,
}

/// TCP 连接统计
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TcpStats {
    /// 活跃连接数
    pub active_connections: u32,
    /// 监听端口数
    pub listening_ports: u32,
    /// 已建立连接数
    pub established: u32,
    /// 等待关闭连接数
    pub time_wait: u32,
}

/// 进程信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessInfo {
    /// 进程ID
    pub pid: u32,
    /// 进程名称
    pub name: String,
    /// CPU使用率（百分比）
    pub cpu_percent: f64,
    /// 内存使用量 (MB)
    pub memory_mb: u64,
    /// 运行时间（秒）
    pub runtime_secs: u64,
    /// 状态
    pub status: String,
    /// 用户
    pub user: Option<String>,
}

impl SystemInfoCollector {
    /// 创建新的系统信息收集器
    pub fn new(cache_ttl: Duration) -> Self {
        Self {
            cache: Arc::new(RwLock::new(SystemInfoCache {
                info: Self::create_empty_info(),
                last_updated: UNIX_EPOCH,
            })),
            cache_ttl,
        }
    }

    /// 获取系统信息（带缓存）
    pub async fn get_system_info(&self) -> AdminResult<SystemInformation> {
        let now = SystemTime::now();
        
        // 检查缓存是否过期
        {
            let cache = self.cache.read().await;
            if now.duration_since(cache.last_updated).unwrap_or(Duration::MAX) < self.cache_ttl {
                return Ok(cache.info.clone());
            }
        }
        
        // 收集新的系统信息
        let info = self.collect_system_info().await?;
        
        // 更新缓存
        {
            let mut cache = self.cache.write().await;
            cache.info = info.clone();
            cache.last_updated = now;
        }
        
        Ok(info)
    }

    /// 收集系统信息
    async fn collect_system_info(&self) -> AdminResult<SystemInformation> {
        // 注意：这里使用了模拟数据，实际实现需要使用 sysinfo crate 等系统调用
        
        let basic = BasicInfo {
            hostname: gethostname::gethostname().to_string_lossy().to_string(),
            os_name: "Linux".to_string(), // 实际中从 std::env::consts::OS 获取
            os_version: "Ubuntu 22.04".to_string(),
            architecture: std::env::consts::ARCH.to_string(),
            kernel_version: "5.15.0".to_string(),
            boot_time: 1640995200, // Unix 时间戳
            uptime_secs: 86400 * 7, // 7天
        };

        let cpu = CpuInfo {
            cores: num_cpus::get_physical(),
            logical_cores: num_cpus::get(),
            model: "Intel Core i7-9700K".to_string(),
            frequency_mhz: 3600.0,
            usage_percent: 25.5,
            load_average: [0.5, 0.6, 0.7],
        };

        let memory = MemoryInfo {
            total_mb: 16384,
            available_mb: 8192,
            used_mb: 6144,
            free_mb: 2048,
            cached_mb: 4096,
            buffers_mb: 512,
            usage_percent: 62.5,
            swap_total_mb: 4096,
            swap_used_mb: 256,
        };

        let disks = vec![
            DiskInfo {
                name: "/dev/sda1".to_string(),
                mount_point: "/".to_string(),
                filesystem: "ext4".to_string(),
                total_gb: 500,
                used_gb: 225,
                available_gb: 275,
                usage_percent: 45.0,
                read_only: false,
            }
        ];

        let hardware = HardwareInfo {
            cpu,
            memory,
            disks,
        };

        let performance = PerformanceMetrics {
            cpu_temperature: Some(65.0),
            system_load: 1.2,
            network_io: NetworkIo {
                bytes_received: 1024 * 1024 * 100, // 100MB
                bytes_sent: 1024 * 1024 * 50,      // 50MB
                packets_received: 10000,
                packets_sent: 8000,
                errors: 2,
            },
            disk_io: DiskIo {
                read_bytes: 1024 * 1024 * 200,  // 200MB
                write_bytes: 1024 * 1024 * 150, // 150MB
                read_count: 5000,
                write_count: 3000,
                io_time_ms: 1500,
            },
            process_stats: ProcessStats {
                total_processes: 156,
                running_processes: 3,
                sleeping_processes: 150,
                zombie_processes: 0,
            },
        };

        let network = NetworkInfo {
            interfaces: vec![
                NetworkInterface {
                    name: "eth0".to_string(),
                    ip_addresses: vec!["192.168.1.100".to_string()],
                    mac_address: Some("00:11:22:33:44:55".to_string()),
                    is_up: true,
                    bytes_received: 1024 * 1024 * 100,
                    bytes_sent: 1024 * 1024 * 50,
                }
            ],
            tcp_connections: TcpStats {
                active_connections: 25,
                listening_ports: 8,
                established: 20,
                time_wait: 5,
            },
        };

        let processes = vec![
            ProcessInfo {
                pid: 1234,
                name: "rustcloud-server".to_string(),
                cpu_percent: 15.2,
                memory_mb: 256,
                runtime_secs: 3600,
                status: "Running".to_string(),
                user: Some("rustcloud".to_string()),
            }
        ];

        // 过滤环境变量，排除敏感信息
        let mut environment = HashMap::new();
        for (key, value) in std::env::vars() {
            if !self.is_sensitive_env_var(&key) {
                environment.insert(key, value);
            }
        }

        Ok(SystemInformation {
            basic,
            hardware,
            performance,
            network,
            processes,
            environment,
        })
    }

    /// 检查是否为敏感环境变量
    fn is_sensitive_env_var(&self, key: &str) -> bool {
        let sensitive_patterns = [
            "PASSWORD", "SECRET", "TOKEN", "KEY", "PRIVATE",
            "AUTH", "CREDENTIAL", "PASS", "PWD", "API_KEY"
        ];
        
        let key_upper = key.to_uppercase();
        sensitive_patterns.iter().any(|pattern| key_upper.contains(pattern))
    }

    /// 创建空的系统信息
    fn create_empty_info() -> SystemInformation {
        SystemInformation {
            basic: BasicInfo {
                hostname: String::new(),
                os_name: String::new(),
                os_version: String::new(),
                architecture: String::new(),
                kernel_version: String::new(),
                boot_time: 0,
                uptime_secs: 0,
            },
            hardware: HardwareInfo {
                cpu: CpuInfo {
                    cores: 0,
                    logical_cores: 0,
                    model: String::new(),
                    frequency_mhz: 0.0,
                    usage_percent: 0.0,
                    load_average: [0.0, 0.0, 0.0],
                },
                memory: MemoryInfo {
                    total_mb: 0,
                    available_mb: 0,
                    used_mb: 0,
                    free_mb: 0,
                    cached_mb: 0,
                    buffers_mb: 0,
                    usage_percent: 0.0,
                    swap_total_mb: 0,
                    swap_used_mb: 0,
                },
                disks: Vec::new(),
            },
            performance: PerformanceMetrics {
                cpu_temperature: None,
                system_load: 0.0,
                network_io: NetworkIo {
                    bytes_received: 0,
                    bytes_sent: 0,
                    packets_received: 0,
                    packets_sent: 0,
                    errors: 0,
                },
                disk_io: DiskIo {
                    read_bytes: 0,
                    write_bytes: 0,
                    read_count: 0,
                    write_count: 0,
                    io_time_ms: 0,
                },
                process_stats: ProcessStats {
                    total_processes: 0,
                    running_processes: 0,
                    sleeping_processes: 0,
                    zombie_processes: 0,
                },
            },
            network: NetworkInfo {
                interfaces: Vec::new(),
                tcp_connections: TcpStats {
                    active_connections: 0,
                    listening_ports: 0,
                    established: 0,
                    time_wait: 0,
                },
            },
            processes: Vec::new(),
            environment: HashMap::new(),
        }
    }

    /// 获取CPU使用率
    pub async fn get_cpu_usage(&self) -> AdminResult<f64> {
        let info = self.get_system_info().await?;
        Ok(info.hardware.cpu.usage_percent)
    }

    /// 获取内存使用率
    pub async fn get_memory_usage(&self) -> AdminResult<f64> {
        let info = self.get_system_info().await?;
        Ok(info.hardware.memory.usage_percent)
    }

    /// 获取磁盘使用率
    pub async fn get_disk_usage(&self) -> AdminResult<Vec<(String, f64)>> {
        let info = self.get_system_info().await?;
        let usage: Vec<(String, f64)> = info.hardware.disks
            .iter()
            .map(|disk| (disk.mount_point.clone(), disk.usage_percent))
            .collect();
        Ok(usage)
    }
}

impl Default for SystemInfoCollector {
    fn default() -> Self {
        Self::new(Duration::from_secs(30)) // 默认30秒缓存
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_system_info_collector() {
        let collector = SystemInfoCollector::new(Duration::from_secs(1));
        
        let info = collector.get_system_info().await.unwrap();
        assert!(!info.basic.hostname.is_empty());
        assert!(info.hardware.cpu.logical_cores > 0);
        assert!(info.hardware.memory.total_mb > 0);
    }

    #[tokio::test]
    async fn test_cpu_usage() {
        let collector = SystemInfoCollector::default();
        let usage = collector.get_cpu_usage().await.unwrap();
        assert!(usage >= 0.0 && usage <= 100.0);
    }

    #[tokio::test]
    async fn test_memory_usage() {
        let collector = SystemInfoCollector::default();
        let usage = collector.get_memory_usage().await.unwrap();
        assert!(usage >= 0.0 && usage <= 100.0);
    }

    #[test]
    fn test_sensitive_env_var_detection() {
        let collector = SystemInfoCollector::default();
        
        assert!(collector.is_sensitive_env_var("DATABASE_PASSWORD"));
        assert!(collector.is_sensitive_env_var("JWT_SECRET"));
        assert!(collector.is_sensitive_env_var("API_KEY"));
        
        assert!(!collector.is_sensitive_env_var("HOME"));
        assert!(!collector.is_sensitive_env_var("PATH"));
        assert!(!collector.is_sensitive_env_var("RUST_LOG"));
    }
}